/*
Copyright 2013 Lin, Chung-Ming (aka Alva Lin. E-mail: alva0930@gmail.com)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import org.apache.hadoop.io.*;

/**
 * A sub-class of org.apache.hadoop.io.ArrayWritable used to contain a double array.
 *
 * @author	Lin, Chung-Ming (aka Alva Lin. E-mail: alva0930@gmail.com)
 */
public class DoubleArrayWritable extends ArrayWritable
{
/* ------------------------
   Constructors
 * ------------------------ */

	/**
	 * For Hadoop internal use only.
	 */
	public DoubleArrayWritable()
	{
		super(DoubleWritable.class);
	}

	/**
	 * Construct a DoubleArrayWritable from a double array.
	 *
	 * @param	values	the double array used to construct the DoubleArrayWritable
	 */
	public DoubleArrayWritable(double[] values)
	{
		super(DoubleWritable.class);
		Writable[] wa = new Writable[values.length];
		for (int i = 0; i < wa.length; i++)
		{
			wa[i] = new DoubleWritable(values[i]);
		}
		super.set(wa);
	}

/* ------------------------
   Public Methods
 * ------------------------ */

	/**
	 * Get the double array represented by this DoubleArrayWritable.
	 *
	 * @return	the double array represented by this DoubleArrayWritable
	 */
	public double[] getDoubleArray()
	{
		Writable[] wa = super.get();
		double[] values = new double[wa.length];
		for (int i = 0; i < values.length; i++)
		{
			values[i] = ((DoubleWritable)wa[i]).get();
		}
		return values;
	}

	/**
	 * Return the csv(comma-separated values) {@link String} representation of this DoubleArrayWritable.
	 *
	 * @return	the csv(comma-separated values) {@link String} representation of this DoubleArrayWritable
	 */
	public String toString()
	{
		StringBuffer sb = null;
		for (double d : getDoubleArray())
		{
			if (null == sb)
			{
				sb = new StringBuffer();
			}
			else
			{
				sb.append(",");
			}
			sb.append("" + d);
		}
		return sb.toString();
	}
}